package com.adam.example;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ShardStatistics;
import co.elastic.clients.elasticsearch._types.mapping.DateProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TextProperty;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.elasticsearch.indices.get_alias.IndexAliases;
import co.elastic.clients.elasticsearch.indices.get_mapping.IndexMappingRecord;
import co.elastic.clients.transport.endpoints.BooleanResponse;

import java.io.IOException;
import java.util.Map;

public class IndicesAdminExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient elasticsearchClient = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();
        ElasticsearchIndicesClient indicesClient = elasticsearchClient.indices();

        BooleanResponse existsResponse = indicesClient.exists(new ExistsRequest.Builder().index("test_books").build());
        System.out.println("索引是否存在：" + existsResponse.value());

        CreateIndexResponse createIndexResponse = indicesClient.create(builder -> builder
                .index("test_create").settings(IndexSettings.of(settingsBuilder -> settingsBuilder
                        .numberOfShards("1").numberOfReplicas("0")
                ))
        );
        System.out.println("创建索引：" + createIndexResponse.acknowledged());

        PutIndicesSettingsResponse putIndicesSettingsResponse = indicesClient.putSettings(builder -> builder
                .index("test_create").settings(indexSettingsBuilder -> indexSettingsBuilder
                        .numberOfReplicas("0")
                )
        );
        System.out.println("更新索引settings: " + putIndicesSettingsResponse.acknowledged());

        GetIndicesSettingsResponse getIndicesSettingsResponse = indicesClient.getSettings(builder -> builder
                .index("test_create")
        );
        IndexState indexState = getIndicesSettingsResponse.get("test_create");
        if(indexState != null) {
            IndexSettings indexSettings = indexState.settings();
            if(indexSettings != null) {
                //index方法与REST Api结构保持一致
                IndexSettings indexSettings1 = indexSettings.index();
                if(indexSettings1 != null) {
                    System.out.println("获取索引settings: numberOfShards=" + indexSettings1.numberOfShards() +
                            ",numberOfReplicas=" + indexSettings1.numberOfReplicas());
                }
            }
        }

        PutMappingResponse putMappingResponse = indicesClient.putMapping(builder -> builder
                .index("test_create")
                .properties("name", Property.of(propertyBuilder -> propertyBuilder.text(
                        TextProperty.of(textPropertyBuilder -> textPropertyBuilder)
                )))
                .properties("date", Property.of(propertyBuilder -> propertyBuilder.date(
                        DateProperty.of(datePropertyBuilder -> datePropertyBuilder.format("yyyy-MM-dd"))
                )))
        );
        System.out.println("更新索引mapping:" + putMappingResponse.acknowledged());

        GetMappingResponse getMappingResponse = indicesClient.getMapping(builder -> builder.index("test_create"));
        IndexMappingRecord indexMappingRecord = getMappingResponse.get("test_create");
        if(indexMappingRecord != null) {
            TypeMapping typeMapping = indexMappingRecord.mappings();
            Map<String, Property> propertyMap = typeMapping.properties();
            for(Map.Entry<String, Property> entry: propertyMap.entrySet()) {
                String key = entry.getKey();
                Property property = entry.getValue();
                System.out.println("获取索引mapping:字段=" + key + ",类型=" + property._kind().jsonValue());
            }
        }

        RefreshResponse refreshResponse = indicesClient.refresh(builder -> builder
                .index("test_create")
        );
        ShardStatistics shardStatistics = refreshResponse.shards();
        System.out.println("刷新索引：总分片数=" + shardStatistics.total() + ",成功数=" + shardStatistics.successful());

        CloseIndexResponse closeIndexResponse = indicesClient.close(builder -> builder
                .index("test_create")
        );
        System.out.println("关闭索引：" + closeIndexResponse.acknowledged());

        OpenResponse openResponse = indicesClient.open(builder -> builder
                .index("test_create")
        );
        System.out.println("开启索引：" + openResponse.acknowledged());

        PutAliasResponse putAliasResponse = indicesClient.putAlias(builder -> builder
                .index("test_create").name("test_create_1")
        );
        System.out.println("添加索引别名：" + putAliasResponse.acknowledged());

        GetAliasResponse getAliasResponse = indicesClient.getAlias(builder -> builder
                .index("test_create")
        );
        System.out.println("获取索引对应的别名：" + getAliasResponse.get("test_create").aliases());

        GetAliasResponse getAliasResponse1 = indicesClient.getAlias(builder -> builder
                .name("test_create_1")
        );
        Map<String, IndexAliases> indexAliasesMap = getAliasResponse1.result();
        System.out.println("获取别名对应的索引：" + indexAliasesMap.keySet().toArray()[0]);

        DeleteIndexResponse deleteIndexResponse = indicesClient.delete(builder -> builder
                .index("test_create")
        );
        System.out.println("删除索引：" + deleteIndexResponse.acknowledged());

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
